import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AppHttpResponse, AppSearchParam } from './interface';

export interface Message {
  id: number;
  title: string;
  content: string;
  createUser: {
    id: number;
    name: string;
  };
  createTime: string;
  imageUrl: string;
  isRead: boolean;
}

@Injectable({
  providedIn: 'root',
})
export class TemplateService {
  // 未读消息数，可观察对象
  unreadMessageCount = new BehaviorSubject(0);

  constructor(private http: HttpClient) {}

  /**
   * 获取消息列表
   * @param searchParam 分页搜索参数
   */
  getMessageList(
    searchParam: AppSearchParam
  ): Observable<AppHttpResponse<any[]>> {
    return this.http
      .post<AppHttpResponse<any[]>>('/api/message/list', searchParam)
      .pipe(
        // 此处为模拟数据，仅对当前分页未读消息做统计
        tap((res) => {
          if (res.success) {
            // 对当前分页未读消息统计
            const count = res.data.reduce((sum: number, item: any) => {
              if (item.isRead) {
                return sum;
              } else {
                return ++sum;
              }
            }, 0);
            // 统计结果发送到数据流中
            this.unreadMessageCount.next(count);
          }
        })
      );
  }

  /**
   * 新增或修改消息
   * @param data 编辑数据
   */
  saveMessage(data: any): Observable<AppHttpResponse<Message>> {
    return this.http.post<AppHttpResponse<Message>>('/api/message/edit', data);
  }

  /**
   * 删除消息
   * @param id 根据 ID 删除数据
   */
  deleteMessage(id: number): Observable<AppHttpResponse<any>> {
    return this.http.delete<AppHttpResponse<any>>('/api/message/delete/' + id);
  }

  /**
   * 检测昵称是否可用
   * @param name 昵称
   */
  checkNickname(name: string): Observable<AppHttpResponse<any>> {
    return this.http.post<AppHttpResponse<any>>('/api/user/checkname', {
      name,
    });
  }

  /**
   * 获取用户列表
   */
  getUserList(): Observable<AppHttpResponse<any[]>> {
    return this.http.get<AppHttpResponse<any[]>>('/api/user/all');
  }

  /**
   * 文件上传
   * @param data FormData 数据
   */
  upload(data: FormData): Observable<AppHttpResponse<any>> {
    return this.http.post<AppHttpResponse<any>>('/api/upload', data);
  }

  /**
   * 获取树形表
   */
  getTreeData(): Observable<AppHttpResponse<any[]>> {
    return this.http.get<AppHttpResponse<any[]>>('/api/tree_data/list');
  }

  /**
   * 获取树节点
   */
  getTreeNode(): Observable<AppHttpResponse<any>> {
    return this.http.get<AppHttpResponse<any>>('/api/tree_data/get');
  }
}
